# -*- coding: utf-8 -*-

from django import forms

from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

from django.conf import settings

from form_utils.forms import BetterModelForm

from core.utils import birth_date_matcher

from student.models import EnrollmentSheet, Student, get_old_enrollment_sheet
from exams.models import Exam, Subject, SubjectYear, ExamApplication, Executor
from core.models import CourseGroup

class EnrollmentSheetEntry(BetterModelForm):
  def __init__(self, *args, **kwargs):
    super(EnrollmentSheetEntry, self).__init__(*args, **kwargs)
    
    if self.is_bound:
      if birth_date_matcher.match(args[0].get('emso', '')):
        try:
          student = Student.objects.get(pk = args[0]['student'])
          self.student = student
        except:
          pass
      else:
        old_enrollment_sheet = get_old_enrollment_sheet(args[0].get('emso', ''))
        if old_enrollment_sheet:
          self.student = old_enrollment_sheet.student
  
  def clean(self):
    try:
      student = self.student
    except:
      student = None
    cleaned_data = self.cleaned_data
    
    if self.is_bound and student:
      if EnrollmentSheet.objects.filter(student = student,
                                        academic_year = cleaned_data['academic_year'],
                                        student_program = cleaned_data['student_program'],
                                        student_year = cleaned_data['student_year'],
                                        student_course_group = cleaned_data['student_course_group']).exists():
        raise ValidationError(u'Študent je že vpisan v to šolsko leto, z izbranim letnikom, programom in smerjo.')
    
    return cleaned_data
  
  def save(self):
    enrollment_sheet = super(EnrollmentSheetEntry, self).save(commit = False)
    try:
      enrollment_sheet.student = self.student
    except:
      pass
    enrollment_sheet.save()
  
  class Meta:
    model = EnrollmentSheet
    fieldsets = (
      (u'Osnovni podatki o študentu', {
        'fields': ('first_name', 'last_name', 'maiden_name', 'image', 'emso', 'vat_number', 'special_needs',)
      }),
      (u'Kontaktne informacije', {
        'fields': ('email', 'telephone',)
      }),
      (u'Stalno prebivališče', {
        'fields': ('permanent_street', 'permanent_postal_number', 'permanent_commune', 'country',)
      }),
      (u'Začasno prebivališče', {
        'fields': ('temporary_street', 'temporary_postal_number', 'temporary_commune',)
      }),
      (u'Informacije o študiju', {
        'fields': ('institution', 'student_program', 'student_course_group', 'student_group', 'academic_year', 'study_type', 'student_year', 'full_time_student', 'enrollment_type')
      }),
      (u'Dodatne informacije o študiju', {
        'fields': ('distance_education', 'studying_location', 'additional_studying_insitution',)
      }),
    )
    
class AllSubjectsSelection(forms.Form):
  subject = forms.ModelChoiceField(label = u'Predmet', queryset = Subject.objects.all());
  finished = forms.ChoiceField(
	label=u'Brez tistih, ki so že opravili izpit', 
	choices=(('False','Ne'),('True','Da'))
	);
  query_set = SubjectYear.objects.values_list('school_year_start').distinct().order_by('-school_year_start');
  year_only = [(i[0], i[0]) for i in query_set]
  year = forms.ChoiceField(label = u'Študijsko leto', choices=year_only);
  year_only = [i[0] for i in query_set]
  year_combo = forms.ChoiceField(
	label = u'Število študijskih let do trenutno izbranega študijskega leta(vključno)', 
	choices=((1, 1),(2, 2))
	)
    
class ExamGradeForm(forms.ModelForm):
  class Meta:
    model = ExamApplication
    fields = ('exam_grade','practice_grade','grade_date')
    
class ExamGradeCreateExamForm(forms.ModelForm):

  def __init__(self, *args, **kwargs):
    subject = kwargs.pop('subject', None)
    professor = kwargs.pop('professor', None)
    super(ExamGradeCreateExamForm, self).__init__(*args, **kwargs)
    if subject:
      pchoices = subject.executors_choices()
      if professor:
        pchoices_tmp = []
        for (k,v) in pchoices:
          if unicode(v).find(unicode(professor)) > -1:
            pchoices_tmp.append((k,v))
        pchoices = pchoices_tmp
      self.fields["executor"] = forms.ChoiceField(label=u'Izvajalec', choices=pchoices);
     
  def clean(self):
    cleaned_data = self.cleaned_data
    if cleaned_data.has_key('executor') and int(cleaned_data['executor']) > 0:
      cleaned_data['executor'] = Executor.objects.get(pk=cleaned_data['executor'])
    return cleaned_data

    
  class Meta:
    model = Exam
    fields = ('subject','executor','date')